package com.zhilei.mq;

import com.rabbitmq.client.Channel;
import com.zhilei.untils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * sms死信队列进行监听
 *
 * @author 志磊
 */
@Slf4j
@Component
public class RabbitMQSMSConsumer_Dead {

    @Autowired
    private SmsUtils smsUtils;

    /**
     * 消费端自动确认
     *
     * @param playLoad 队列收到的消息
     * @param message  存储的载体
     */
//    @RabbitListener(queues = {RabbitMQConfig_Dead.SMS_QUEUE_DEAD})
//    public void watchQueue(String playLoad, Message message) {
//
//        System.out.println("开始进入死信队列！");
//
//        log.info("Receive message from RabbitMQ: {}", message);
//        log.info("Receive playLoad from playLoad: {}", playLoad);
//
//        // 获取路由key
//        String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
//        log.info("Receive receivedRoutingKey from receivedRoutingKey: {}", receivedRoutingKey);
//
//        System.out.println("结束死信队列！");
//    }

    /**
     * 消费端开启手动的ACK确认
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
    public void watchQueue(Message message, Channel channel) throws Exception {
        long deliveryTag = 0;
        try {
            log.info("Receive message from RabbitMQ: {}", message);

            // 获取路由key
            String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
            log.info("Receive receivedRoutingKey from receivedRoutingKey: {}", receivedRoutingKey);

            // 获取sms消息
            byte[] body = message.getBody();
            String msg = new String(body);
            log.info("msg" + msg);

            // 确认消息
            deliveryTag = message.getMessageProperties().getDeliveryTag();
            // 确认发送成功
            /**
             * 第一参数是消息投递标签
             * 第二个参数是当true时批量执行，false不会批量确认
             */
            channel.basicAck(deliveryTag, true);
            System.out.println("短信发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
            // 消息发送失败重新发送
            /**
             * 第一参数是消息投递标签
             * 第二个参数是当true时批量执行，false不会批量确认
             * requeue: true：重新回到队列, false：丢弃消息
             *
             */
            channel.basicNack(deliveryTag, true, false);
        }
    }
}
